package com.cube.share.idempotence.util;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author cube.li
 * @date 2021/6/27 22:10
 * @description HttpServletRequest工具类
 */
@Slf4j
public class RequestUtil {

    /**
     * 从当前请求中获取请求属性
     * 先从请求头中获取,如果请求头中没有则从Cookie中获取,最后从请求参数中获取
     *
     * @param attributeName 属性名
     * @return
     */
    @Nullable
    public static String getRequestAttribute(@NonNull String attributeName) {
        HttpServletRequest currentRequest = currentRequest();
        if (currentRequest == null) {
            return null;
        }

        String header = currentRequest.getHeader(attributeName);
        if (StringUtils.isNotBlank(header)) {
            return header;
        }

        Cookie[] cookies = currentRequest.getCookies();
        if (ArrayUtils.isEmpty(cookies)) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(attributeName)) {
                return cookie.getValue();
            }
        }

        return currentRequest.getParameter(attributeName);
    }

    public static HttpServletRequest currentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attributes.getRequest();
    }
}
